package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.ConfirmOrderAdapter;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.ProductModel;
import com.tiantianyuegou.model.StoreModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.ToastUtilsCenter;
import com.tiantianyuegou.util.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 确认订单界面
 * Created by ivany on 2016/1/12.
 */
public class ConfirmOrderActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {


    private TextView mTxt_consigneeName, mTxt_consigneePhone, mTxt_consigneeAddress,
            mTxt_sum, mTxt_freight, mTxt_operation;

    private LinearLayout mLinear_noAddress, mLinear_haveAddress;

    private ListView mListView;
    private ConfirmOrderAdapter mAdapter;
    List<StoreModel> mData;
    List<StoreModel> mTransData;
    private int mPostion;

    private Double mUnitPrice = 1d;
    private Double mCoupon = 0d;//优惠券
    private boolean isChangeCoupon = false;//选址优惠券
    private boolean hasSelectAddress = false;//是否已经选择收货地址
    private int mAddressId;
    private String mWhereIn;
   LoadingDialog mLoadingDialog;

    //记录上次选择的优惠券
    public static List<Map<Integer, Integer>> LAST_CHOOSE_COUPON;

    //记录上次选择的收获地址id
    public static int LAST_CHOOSE_ADDRESS;

    private int count;//使用的贯个数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        Tools.changeSystemBar(this);
        setTitle("确认订单");
        initViews();

        //将activity加入栈
        SysApplication.getInstance().addActivity(this);
    }

    @Override
    public void findViewByIds() {
        mTxt_freight = (TextView) findViewById(R.id.confirm_freight);
        mTxt_sum = (TextView) findViewById(R.id.confirm_sum);
        mTxt_operation = (TextView) findViewById(R.id.confirm_operation);
        mListView = (ListView) findViewById(R.id.confirm_list);
    }

    @Override
    public void initListener() {
        mListView.setOnItemClickListener(this);
        mTxt_operation.setOnClickListener(this);
        mLoadingDialog = new LoadingDialog(this);
    }

    @Override
    public void initData() {
        LAST_CHOOSE_COUPON = new ArrayList<>();
        LAST_CHOOSE_ADDRESS = 0;
        addHead();
        getDefaultAddress();//获取用户的默认地址
        mData = new ArrayList<>();
        Intent intent = getIntent();
        mWhereIn = intent.getStringExtra("whereIn");
        mUnitPrice = Double.valueOf(intent.getStringExtra("unitPrice"));
        //判断是否是从购物车结算跳转过来
        if (intent.getStringExtra("type").equals("account")) {
            mTransData = (List<StoreModel>) getIntent().getSerializableExtra("mTransData");
            mData.addAll(mTransData);
            reCount(mData);
        }
        //判断是否点击 立即购买
        else if (intent.getStringExtra("type").equals("buy")) {
            List<StoreModel> storeModels = (ArrayList<StoreModel>) intent.getSerializableExtra("orderInfo");
            mData.addAll(storeModels);
            reCount(mData);
        }
        mAdapter = new ConfirmOrderAdapter(ConfirmOrderActivity.this, mData);
        mListView.setAdapter(mAdapter);
        mAdapter.setSelectCouponListener(new ConfirmOrderAdapter.ISelectCouponListener() {
            @Override
            public void selectCoupon(int position) {
                //将上次记录的优惠券值置为选择的优惠券的id(在选择优惠券后又选择了商品数量的时候重新记录
                // 此时会将改商店下的优惠券id置为-1)；
                for(int i=0;i<LAST_CHOOSE_COUPON.size();i++){
                    if(LAST_CHOOSE_COUPON.get(i).containsKey(mData.get(position).getStoreId())){
                        LAST_CHOOSE_COUPON.get(i).put(mData.get(position).getStoreId(),mData.get(position).getCouponId());
                    }
                }
                isChangeCoupon = position == mPostion ? true : false;
                mPostion = position;
                Intent intent = new Intent(ConfirmOrderActivity.this, SelectCouponActivity.class);
                intent.putExtra("storeId", mData.get(position).getStoreId());
                intent.putExtra("account",mData.get(position).getAccount());
                startActivityForResult(intent, Constant.SELECT_COUPON_REQUEST);
            }

            @Override
            public void reCalcuate(List<StoreModel> mData) {
                reCount(mData);
            }
        });

    }

    //重新计算价格
    private void reCount(List<StoreModel> mData) {
        Double mCoupon=0d;
        Double price = 0d;
        count = 0;
        Double productValue = 0d;
        Double freight = 0d;
        for (int i = 0; i < mData.size(); i++) {
            mCoupon+=Double.valueOf(mData.get(i).getCoupon());
            count += Integer.valueOf(mData.get(i).getUseGuanVlaue());//获取使用的贯
            freight += Double.valueOf(mData.get(i).getExpress());//获取运费
            List<ProductModel> products = mData.get(i).getProductModels();
            for (int j = 0; j < products.size(); j++) {
                Integer num = Integer.valueOf(products.get(j).getNumber());//获取每件商品的个数
                Double value = Double.valueOf(products.get(j).getPrice().substring(1));//获取每件商品的单价
//                Log.e("TAG", "num:" + num + ":value:" + value);
                productValue += (num * value);//计算商品的总价
            }
            mData.get(i).setAccount(productValue);//将这家店中购买的商品的价格加起来
        }
        String totalGuna = SPHelper.getTmGuanCount();
        if (totalGuna != null && !"".equals(totalGuna)) {
            if (count > Integer.valueOf(totalGuna)) {
                ToastUtilsCenter.makeText(this, "您的贯数不足", false).show();
                mTxt_operation.setEnabled(false);
            } else {
                mTxt_operation.setEnabled(true);
            }
        }
        price = (productValue - (count * mUnitPrice) - mCoupon + freight);//重新计算总价（商品价格-贯-优惠券+快递）
//        Log.e("TAG","price:"+price);
        if (price <= 0) {
            mTxt_sum.setText("￥0.00");
        } else {
            mTxt_sum.setText("￥" + new DecimalFormat("0.00").format(price));
        }
        mTxt_freight.setText("(含运费￥" + new DecimalFormat("0.00").format(freight) + ")");
    }

    //listView添加头部布局
    private void addHead() {
        View headView = LayoutInflater.from(this).inflate(R.layout.item_confirm_order_head, mListView, false);
        mTxt_consigneeName = (TextView) headView.findViewById(R.id.confirm_consigneeName_txt);
        mTxt_consigneePhone = (TextView) headView.findViewById(R.id.confirm_consigneePhone_txt);
        mTxt_consigneeAddress = (TextView) headView.findViewById(R.id.confirm_receiver_address);
        mLinear_haveAddress = (LinearLayout) headView.findViewById(R.id.confirm_location_linear);
        mLinear_noAddress = (LinearLayout) headView.findViewById(R.id.confirm_location_no_address);

        mListView.addHeaderView(headView);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            Intent intent = new Intent(ConfirmOrderActivity.this, SelectAddressActivity.class);
            intent.putExtra("id", "confirm");
            startActivityForResult(intent, Constant.SELECT_ADDRESS_REQUEST);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.SELECT_ADDRESS_REQUEST) {
            if (resultCode == Constant.SELECT_ADDRESS_RESULT) {
                hasSelectAddress = true;
                mLinear_noAddress.setVisibility(View.GONE);
                mLinear_haveAddress.setVisibility(View.VISIBLE);
                mAddressId = data.getIntExtra("addressId", 0);
                mTxt_consigneeName.setText(data.getStringExtra("name"));
                mTxt_consigneePhone.setText(data.getStringExtra("phone"));
                mTxt_consigneeAddress.setText(data.getStringExtra("address"));
//                getFreight(data.getStringExtra("cityId"));
            }
        } else if (requestCode == Constant.SELECT_COUPON_REQUEST) {
            if (resultCode == Constant.SELECT_COUPON_RESULT) {
                if (isChangeCoupon) {
                    mCoupon = mCoupon - Double.valueOf(mData.get(mPostion).getCoupon());
                }
                String value = data.getStringExtra("value");
                mData.get(mPostion).setCoupon(value);
                mData.get(mPostion).setCouponId(data.getIntExtra("couponId", 0));
                mCoupon += Double.valueOf(value);//保存优惠券的值
                mAdapter.notifyDataSetChanged();
                reCount(mData);
            }
        }
    }


    //获取默认地址
    private void getDefaultAddress() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ADDRESS_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("TAG", "getAddressList :" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取地址列表失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            JSONArray list = root.getJSONArray("list");
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject value = list.getJSONObject(i);
                                if (1 == value.getInt("tmaDefault")) {
                                    hasSelectAddress = true;
                                    mLinear_noAddress.setVisibility(View.GONE);
                                    mLinear_haveAddress.setVisibility(View.VISIBLE);
                                    mAddressId = value.getInt("tmaId");
                                    mTxt_consigneeName.setText(value.getString("tmaName"));
                                    mTxt_consigneePhone.setText(value.getString("tmaPhone"));
                                    StringBuffer address = new StringBuffer();
                                    address.append(value.getString("provice")).append(" ").append(value.getString("city"))
                                            .append(" ").append(value.getString("county")).append(" ").append(value.getString("tmaAddress"));
                                    mTxt_consigneeAddress.setText(address.toString());
//                                    getFreight(value.getInt("tmaCityId") + "");
                                    break;
                                } else {
                                    mLinear_noAddress.setVisibility(View.VISIBLE);
                                    mLinear_haveAddress.setVisibility(View.GONE);
                                }
                            }
                        } else if ("103".equals(code)) {
                            mLinear_noAddress.setVisibility(View.VISIBLE);
                            mLinear_haveAddress.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }


    /*//根据城市获取运费
    private void getFreight(String cityId) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("cityId", cityId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GET_FREIGHT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("TAG", "getFreight data :" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取邮费失败，请重新选择收货地址");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            JSONObject value = root.getJSONObject("info");
                            Double freight = value.getDouble("trFreight");
                            for (int i = 0; i < mData.size(); i++) {
                                mData.get(i).setExpress(new DecimalFormat("0.00").format(freight));
                            }
                            mAdapter.notifyDataSetInvalidated();
                            reCount(mData);//有邮费后重新计算总价
                        } else if ("103".equals(code)) {
                            showMsg("此地区无运费信息");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }
*/
    //提交订单
    private void submitOrder(String type, String whereIn) {
        StringBuffer tpIds = new StringBuffer();//商品Id
        StringBuffer tscIds = new StringBuffer();//购物车Id
        StringBuffer tpCounts = new StringBuffer();//商品数量
        StringBuffer tpSpecIds = new StringBuffer();//商品的规格id
        StringBuffer tpSpecValueIds = new StringBuffer();//商品的规格值id
        StringBuffer shopIds = new StringBuffer();//店铺id
        StringBuffer ticketIds = new StringBuffer();//优惠券Id
        StringBuffer guangCounts = new StringBuffer();
        for (int i = 0; i < mData.size(); i++) {
            shopIds.append(mData.get(i).getStoreId()).append(",");
            //判断是否有优惠券，当没有的时候传0
            String couponId = String.valueOf(mData.get(i).getCouponId());
            if (couponId == null || "0".equals(couponId)) {
                ticketIds.append("0,");
            } else {
                ticketIds.append(couponId).append(",");
            }
            String guangCount = mData.get(i).getUseGuanVlaue();
            if (guangCount == null || "0".equals(guangCount)) {
                guangCounts.append("0,");
            } else {
                guangCounts.append(guangCount).append(",");
            }
            List<ProductModel> productModels = mData.get(i).getProductModels();
            for (int j = 0; j < productModels.size(); j++) {
                ProductModel productModel = productModels.get(j);
                tpIds.append(productModel.getId()).append(",");
                if(productModel.getTscId()==0){
                    tscIds.append(",");
                }else{
                    tscIds.append(productModel.getTscId()).append(",");
                }
                tpCounts.append(productModel.getNumber()).append(",");
                tpSpecIds.append(productModel.getSpecIds()).append("|");
                tpSpecValueIds.append(productModel.getSepecValueIds()).append("|");
            }
            tpIds.append("|");
            tscIds.append("|");
            tpCounts.append("|");
        }
        RequestParams params = new RequestParams();
//        tmId goodsIds goodsColors goodsSize goodsCounts addressId
//        params.addBodyParameter("tpIds", tpIds.substring(0, tpIds.length() - 2));
//        params.addBodyParameter("tscId",tscIds.substring(0,tscIds.length()-2));
//        params.addBodyParameter("counts", tpCounts.substring(0, tpCounts.length() - 2));
//        params.addBodyParameter("specIds", tpSpecIds.substring(0, tpSpecIds.length() - 1));
//        params.addBodyParameter("specValueIds", tpSpecValueIds.substring(0, tpSpecValueIds.length() - 1));
//        params.addBodyParameter("shopIds", shopIds.substring(0, shopIds.length() - 1));
//        params.addBodyParameter("ticketIds", ticketIds.substring(0, ticketIds.length() - 1));
//        params.addBodyParameter("guang", guangCounts.substring(0, guangCounts.length() - 1));
//        params.addBodyParameter("tmaId", mAddressId + "");
//        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("tmId", 342+"");
        params.addBodyParameter("goodsIds", 130+"");
        params.addBodyParameter("goodsIds", 130+"");
        params.addBodyParameter("goodsColors", "麻辣");
        params.addBodyParameter("goodsSize", "S");
        params.addBodyParameter("goodsCounts", 1+"");
        params.addBodyParameter("addressId", 1+"");
        params.addBodyParameter("wherein", whereIn);
//        Log.e("TAG", "submitOrder params :tpIds:" + tpIds.substring(0, tpIds.length() - 2) +
//                ":tscId:"+tscIds.substring(0,tscIds.length()-2)+
//                ":counts:" + tpCounts.substring(0, tpCounts.length() - 2) +
//                ":specIds:" + tpSpecIds.substring(0, tpSpecIds.length() - 1) +
//                ":specValueIds:" + tpSpecValueIds.substring(0, tpSpecValueIds.length() - 1) +
//                ":shopIds:" + shopIds.substring(0, shopIds.length() - 1) +
//                ":ticketIds:" + ticketIds.substring(0, ticketIds.length() - 1) +
//                ":guang:" + guangCounts.substring(0, guangCounts.length() - 1) +
//                ":tmaId:" + mAddressId +
//                ":tmId:" + SPHelper.getTmId() +
//                ":type:" + type + ":whereIn:" + whereIn);

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ADD_ORDER, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();

                Log.e("TAG", "submit Order response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("订单提交失败!");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            //订单提交成功后更改总贯数
                            int totalGuna = Integer.parseInt(SPHelper.getTmGuanCount());
                            SPHelper.setTmGuanCount((totalGuna - count) + "");

                            Intent intent = new Intent(ConfirmOrderActivity.this, PayActivity.class);
                            String orderNo = root.getString("toNumber");
                            String orderId = root.getString("toId");
                            intent.putExtra("orderNo", orderNo);
                            intent.putExtra("orderId", orderId);
                            intent.putExtra("value", mTxt_sum.getText().toString());
                            startActivity(intent);
                        } else if ("200".equals(code)) {
                            showMsg("您不能购买自家的商品");
                        } else {
                            showMsg("提交订单失败!");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm_operation:
                if (hasSelectAddress) {
                    mLoadingDialog.show();
                    submitOrder("1", mWhereIn);
//                    Intent intent = new Intent(ConfirmOrderActivity.this, PayActivity.class);
//                    intent.putExtra("value", mTxt_sum.getText().toString());
//                    startActivity(intent);
                } else {
                    Toast.makeText(this, "请先选择收货地址", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
